package com.todo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.todo.dto.TodoRequest;
import com.todo.entity.Todo;
import com.todo.mapper.TodoMapper;
import com.todo.service.TodoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 待办事项服务实现类
 */
@Service
public class TodoServiceImpl implements TodoService {

    @Autowired
    private TodoMapper todoMapper;

    @Override
    public Todo createTodo(Long userId, TodoRequest request) {
        Todo todo = new Todo();
        BeanUtils.copyProperties(request, todo, "priority"); // 排除priority字段，手动处理
        todo.setUserId(userId);
        todo.setStatus(0); // 待完成
        
        // 处理优先级转换
        todo.setPriority(convertPriority(request.getPriority()));
        
        todoMapper.insert(todo);
        return todo;
    }

    @Override
    public Todo updateTodo(Long userId, TodoRequest request) {
        Todo todo = todoMapper.selectById(request.getId());
        if (todo == null || !todo.getUserId().equals(userId)) {
            throw new RuntimeException("待办事项不存在");
        }
        
        BeanUtils.copyProperties(request, todo, "priority"); // 排除priority字段，手动处理
        todo.setUserId(userId); // 确保用户ID不被覆盖
        
        // 处理优先级转换
        todo.setPriority(convertPriority(request.getPriority()));
        
        // 处理完成状态
        if (request.getCompleted() != null) {
            if (request.getCompleted()) {
                todo.setStatus(1); // 已完成
                if (todo.getCompletedAt() == null) {
                    todo.setCompletedAt(LocalDateTime.now());
                }
            } else {
                todo.setStatus(0); // 待完成
                todo.setCompletedAt(null);
            }
        }
        
        todoMapper.updateById(todo);
        return todo;
    }

    @Override
    public void deleteTodo(Long userId, Long todoId) {
        Todo todo = todoMapper.selectById(todoId);
        if (todo == null || !todo.getUserId().equals(userId)) {
            throw new RuntimeException("待办事项不存在");
        }
        
        todo.setStatus(2); // 标记为已删除
        todoMapper.updateById(todo);
    }

    @Override
    public void completeTodo(Long userId, Long todoId) {
        Todo todo = todoMapper.selectById(todoId);
        if (todo == null || !todo.getUserId().equals(userId)) {
            throw new RuntimeException("待办事项不存在");
        }
        
        todo.setStatus(1); // 标记为已完成
        todo.setCompletedAt(LocalDateTime.now());
        todoMapper.updateById(todo);
    }

    @Override
    public void uncompleteTodo(Long userId, Long todoId) {
        Todo todo = todoMapper.selectById(todoId);
        if (todo == null || !todo.getUserId().equals(userId)) {
            throw new RuntimeException("待办事项不存在");
        }
        
        todo.setStatus(0); // 标记为待完成
        todo.setCompletedAt(null); // 清除完成时间
        todoMapper.updateById(todo);
    }

    @Override
    public Todo getTodoById(Long userId, Long todoId) {
        Todo todo = todoMapper.selectById(todoId);
        if (todo == null || !todo.getUserId().equals(userId)) {
            throw new RuntimeException("待办事项不存在");
        }
        return todo;
    }

    @Override
    public List<Todo> getTodoList(Long userId, Integer status) {
        return getTodoList(userId, status, null);
    }

    @Override
    public List<Todo> getTodoList(Long userId, Integer status, String keyword) {
        QueryWrapper<Todo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        if (status != null) {
            queryWrapper.eq("status", status);
        } else {
            queryWrapper.ne("status", 2); // 排除已删除的
        }
        
        // 添加关键词搜索条件
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("title", keyword.trim())
                .or()
                .like("description", keyword.trim())
            );
        }
        
        queryWrapper.orderByDesc("create_time");
        return todoMapper.selectList(queryWrapper);
    }

    @Override
    public List<Todo> searchTodos(Long userId, String keyword, Integer status) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getTodoList(userId, status);
        }
        
        QueryWrapper<Todo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        // 搜索标题和描述
        queryWrapper.and(wrapper -> wrapper
            .like("title", keyword.trim())
            .or()
            .like("description", keyword.trim())
        );
        
        // 添加状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        } else {
            queryWrapper.ne("status", 2); // 排除已删除的
        }
        
        // 按相关性和时间排序
        queryWrapper.orderByDesc("create_time");
        return todoMapper.selectList(queryWrapper);
    }

    @Override
    public List<Todo> getTodosByDate(Long userId, LocalDate date) {
        QueryWrapper<Todo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("due_date", date)
                   .ne("status", 2) // 排除已删除的
                   .orderByAsc("due_time")
                   .orderByDesc("priority");
        return todoMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> getTodoStatistics(Long userId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 待完成数量
        QueryWrapper<Todo> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("user_id", userId).eq("status", 0);
        Long pendingCount = todoMapper.selectCount(pendingWrapper);
        
        // 已完成数量
        QueryWrapper<Todo> completedWrapper = new QueryWrapper<>();
        completedWrapper.eq("user_id", userId).eq("status", 1);
        Long completedCount = todoMapper.selectCount(completedWrapper);
        
        // 今日待完成数量
        QueryWrapper<Todo> todayWrapper = new QueryWrapper<>();
        todayWrapper.eq("user_id", userId)
                   .eq("status", 0)
                   .eq("due_date", LocalDate.now());
        Long todayCount = todoMapper.selectCount(todayWrapper);
        
        statistics.put("pendingCount", pendingCount);
        statistics.put("completedCount", completedCount);
        statistics.put("todayCount", todayCount);
        statistics.put("totalCount", pendingCount + completedCount);
        
        return statistics;
    }

    /**
     * 获取按日期分组的待办事项
     * 返回昨天、今天、明天、后天的待办事项
     * @param userId 用户ID
     * @return 按日期分组的待办事项Map
     */
    @Override
    public Map<String, List<Todo>> getTodosGroupByDate(Long userId) {
        Map<String, List<Todo>> groupedTodos = new HashMap<>();
        
        // 计算各个日期
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);    // 昨天
        LocalDate tomorrow = today.plusDays(1);      // 明天
        LocalDate dayAfterTomorrow = today.plusDays(2); // 后天
        
        // 获取各个日期的待办事项
        groupedTodos.put("yesterday", getTodosByDate(userId, yesterday));
        groupedTodos.put("today", getTodosByDate(userId, today));
        groupedTodos.put("tomorrow", getTodosByDate(userId, tomorrow));
        groupedTodos.put("dayAfterTomorrow", getTodosByDate(userId, dayAfterTomorrow));
        
        return groupedTodos;
    }

    /**
     * 转换优先级字段
     * 将前端传递的字符串优先级转换为数字
     * @param priority 前端传递的优先级（可能是字符串或数字）
     * @return 转换后的数字优先级：1-低 2-中 3-高
     */
    private Integer convertPriority(Object priority) {
        if (priority == null) {
            return 2; // 默认中等优先级
        }
        
        if (priority instanceof Integer) {
            return (Integer) priority;
        }
        
        if (priority instanceof String) {
            String priorityStr = ((String) priority).toLowerCase();
            switch (priorityStr) {
                case "low":
                    return 1;
                case "medium":
                case "normal":
                    return 2;
                case "high":
                    return 3;
                default:
                    return 2; // 默认中等优先级
            }
        }
        
        return 2; // 默认中等优先级
    }
} 